package org.jaronsource.framework.core.web.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class FileServlet extends HttpServlet {

	private static final long serialVersionUID = -4587628773840915247L;

	@Override
	public void init( ServletConfig config ) throws ServletException {
		super.init( config );

	}

	public
			void
			service( HttpServletRequest request, HttpServletResponse response )
																				throws ServletException,
																				IOException {

		String operator = request.getParameter( "operator" );

		String filePath = request.getParameter( "file" );
		filePath = StringUtils.substringAfter( filePath, request.getContextPath() );
		String realFilePath = request.getSession().getServletContext().getRealPath( filePath );

		if ( StringUtils.equals( operator, "del" ) ) {
			doDeleteFile( realFilePath );
		}
		
		if ( StringUtils.equals( operator, "down" ) ) {
			doDownloadFile( realFilePath, response );
		}

	}

	private void doDeleteFile( String realFilePath ) {
		File fileToDelete = new File( realFilePath );
		if ( fileToDelete.exists() ) {
			fileToDelete.delete();
		}
	}

	private void doDownloadFile(	String realFilePath,
									HttpServletResponse response ) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		try {
			File targetFile = new File( realFilePath );
			if ( !targetFile.exists() ) {
				response.setContentType( "text/html;charset=UTF-8" );
				response.getWriter().print( "File not found!" );
				return;
			}

			int index = realFilePath.lastIndexOf( "/" );
			String fileName = realFilePath.substring( index + 1 );

			ServletOutputStream out = response.getOutputStream();
			response.setHeader( "Content-disposition", "attachment;filename=" + fileName );

			bis = new BufferedInputStream( new FileInputStream( realFilePath ) );
			bos = new BufferedOutputStream( out );
			byte[] buff = new byte[2048];
			int bytesRead;
			while ( -1 != ( bytesRead = bis.read( buff, 0, buff.length ) ) ) {
				bos.write( buff, 0, bytesRead );
			}
		}
		catch ( IOException e ) {
			e.printStackTrace();
		}
		finally {
			if ( bis != null ) try {
				bis.close();
			}
			catch ( IOException e ) {
				e.printStackTrace();
			}
			if ( bos != null ) try {
				bos.close();
			}
			catch ( IOException e ) {
				e.printStackTrace();
			}
		}
	}
}